package org.lqk.zookeeper.discovery.server;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.imps.CuratorFrameworkState;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.StringUtils;

/**
 * 注册服务列表到Zookeeper
 */
public class ZookeeperServerAddressRegister
		implements ServerAddressRegister, InitializingBean, DisposableBean {

	private static Logger log = LoggerFactory.getLogger(ZookeeperServerAddressRegister.class);

	private CuratorFramework zkClient;

	public ZookeeperServerAddressRegister() {
	}

	public ZookeeperServerAddressRegister(CuratorFramework zkClient) {
		this.zkClient = zkClient;
	}

	public void setZkClient(CuratorFramework zkClient) {
		this.zkClient = zkClient;
	}

	@Override
	public void register(String service, String version, String address) {
		if (zkClient.getState() == CuratorFrameworkState.LATENT) {
			zkClient.start();
		}
		if (StringUtils.isEmpty(version)) {
			version = "1.0.0";
		}

		try {
			String path = "/" + service + "/" + version + "/" + address;
			// 临时节点，当服务端断开时，该节点会自动消失
//			zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path);
			log.debug("register path {}", path);
			// 本文为了测试，使用永久节点
			zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path);
		} catch (Exception e) {
			log.error("register service address to zookeeper exception");
			log.error(e.getMessage(), e);
		}
	}

	@Override
	public void destroy() throws Exception {
		zkClient.close();
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		log.debug("register");
		register("zkDemo", "1.0.0", "127.0.0.1:8080:1");

	}
}
